/**
 * @ClassName: KaptchaController.java
 * @Package com.vrv.controller.kaptcha
 * @author LQ
 * @date 2017年3月17日 上午1:02:15
 * @version V1.0
 */
package com.vrv.controller.kaptcha;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.vrv.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * KaptchaController:验证码Controller
 * @author LQ
 */
@Controller
public class KaptchaController {

    @Autowired
    private Producer producer;

    /**
     * 生成验证码
     * @param response 当前HTTP响应
     * @param ServletException servlet异常
     * @param IOException IO异常
     * @return void
     */
    @RequestMapping("captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }

}
